package com.example.sxt_practise.IO;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 随机读取和写入流
 * @author gaofeng
 * @date 2022年05月11日 23:44
 */
public class RandomAccessFileTest {
    public static void main(String[] args) {
       /* try (RandomAccessFile raf = new RandomAccessFile(new File("src/IO/User.java"),"r");) {
            byte[] flush = new byte[1024 * 2] ;
            int len = -1;
            raf.seek(3);
            while ((len = raf.read(flush)) != -1) {
                System.out.println(new String(flush, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        File file = new File("src/IO/User.java") ;
        long len = file.length() ;
        int blockSize = 10 ;
        int num = (int) Math.ceil(len * 1.0 / blockSize);
        System.out.println(num);
        readStock();
    }

    /**
     * 分块读取
     * @author gaofeng
     * @date  2022/5/11 23:59
     */
    private static void readStock() {
        try (RandomAccessFile raf = new RandomAccessFile(new File("src/IO/User.java"),"r");) {
            //开始位置
            int beginPos = 3 ;
            // 读取的实际大小
            int actualSize = 10 ;
            //
            byte[] flush = new byte[1024] ;
            int len = -1;
            raf.seek(beginPos);
            while ((len = raf.read(flush)) != -1) {
                // 如果actualSize > len,全部都接收
                if (actualSize > len) {
                    System.out.println(new String(flush, 0, len));
                    actualSize -= len ;
                } else {
                    System.out.println(new String(flush, 0, actualSize));
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
